<template>
    <el-form ref="ruleFormRef" style="max-width: 600px" :model="ruleForm" :rules="rules" label-width="auto">

        <el-form-item label="年级：" prop="level">
            <el-select clearable v-model="ruleForm.level" placeholder="年级" @change="levelChange">
                <el-option :label="item.name" :value="item.value" v-for="item in levelStore.list" :key="item.value" />
            </el-select>
        </el-form-item>
        <el-form-item label="学科: " prop="subject">
            <el-select clearable v-model="ruleForm.subjectId" placeholder="请选择" size="large">
                <el-option v-for="item in arr" :key="item.id" :label="item.name + '(' + item.levelName + ')'"
                    :value="item.name + '(' + item.levelName + ')'" />
            </el-select>
        </el-form-item>

        <el-form-item label="题干：" prop="name">
            <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="选择：" prop="options">
            <el-form-item v-for="(item, idx) in ruleForm.options" :key="idx" :label="String.fromCharCode(65+idx)" :prop="`options.${idx}.content`"
                style="display: flex; align-items: center; white-space: nowrap; margin-bottom: 15px;">
                <el-input v-model="item.prefix" :placeholder="String.fromCharCode(65+idx)" style="width:50px; margin-right: 10px;" disabled />
                <el-input v-model="item.content" style="flex: 1;" placeholder="请输入选项内容" />
                <el-button type="danger" size="small" @click="removeOption(idx)" v-if="ruleForm.options.length > 2" style="margin-left:8px;">删除</el-button>
            </el-form-item>
        </el-form-item>

        <el-form-item label="解析：">
            <el-input />
        </el-form-item>
        <el-form-item label="分数：" prop="score">
            <el-input-number v-model="num" :precision="1" :min="0" :max="100" @change="handleChange" />
        </el-form-item>
        <el-form-item label="难度：" prop="difficulty">
            <div class="demo-rate-block">
                <el-rate v-model="value1" />
            </div>
        </el-form-item>
        <el-form-item label="正确答案：" prop="correctAnswer">
            <el-radio-group v-model="ruleForm.correctAnswer">
                <el-radio v-for="(item, idx) in ruleForm.options" :key="idx" :label="item.prefix" size="large">{{ item.prefix }}</el-radio>
            </el-radio-group>
        </el-form-item>

        <el-form-item>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
                提交
            </el-button>
            <el-button @click="resetForm(ruleFormRef)">重置</el-button>
            <el-button @click="addOption" type="success" style="margin-top: 0;">添加选项</el-button>
            <el-button type="success">预览</el-button>

        </el-form-item>
    </el-form>
</template>

<script lang="ts" setup>
import { ref } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useLevelStore } from "@/stores/level"
import { examAdd, type ExamAddParamsType } from "@/api/exampage"
import { useRouter } from "vue-router"
import axios from 'axios'
const num = ref(1)
const handleChange = (value: number | undefined) => {
    console.log(value)
}
const value1 = ref(0)
const radio1 = ref('1')
//创建路由实例
const router = useRouter()
const arr = ref<any>([])
const id = ref('')

function getsubjectList() {
    axios({
        url: "/api/api/admin/education/subject/list",
        method: "post",
    }).then(res => {
        console.log(res.data, 'subject')
        if (res.data.message == "成功") {
            arr.value = res.data.response
        }
    })

}
getsubjectList()

const subject = ref('')

//pinia 年级的数据
const levelStore = useLevelStore()
//获取elFrom组件
const ruleFormRef = ref<FormInstance>()
// 添加的表单数据
const ruleForm = ref<any>({
    id: null,
    level: '',
    subjectId: '',
    paperType: '',
    levelName: '',
    name: '',
    suggestTime: '',
    options: [
        { prefix: 'A', content: '' },
        { prefix: 'B', content: '' }
    ],
    correctAnswer: ''
})
//验证规则
const rules = ref<FormRules<any>>({
    name: [
        { required: true, message: '请输入题干', trigger: 'blur' },
    ],
    level: [
        { required: true, message: '请选择年级', trigger: 'blur' },
    ],
    options: [
        { type: 'array', min: 2, required: true, message: '请至少填写两个选项', trigger: 'blur' },
        { validator: (rule, value, callback) => {
            if (value.some((v: any) => !v.content)) {
                callback(new Error('所有选项内容不能为空'))
            } else {
                callback()
            }
        }, trigger: 'blur' }
    ],
    correctAnswer: [
        { required: true, message: '请选择正确答案', trigger: 'change' },
        { validator: (rule, value, callback) => {
            const idx = ruleForm.value.options.findIndex((item: any) => item.prefix === value)
            if (idx === -1) {
                callback(new Error('正确答案必须在选项中'))
            } else if (!ruleForm.value.options[idx].content) {
                callback(new Error('正确答案内容不能为空'))
            } else {
                callback()
            }
        }, trigger: 'change' }
    ]
})
//年级变化的事件
function levelChange(val: any) {
    const level = levelStore.list.find(item => item.value == val)
    ruleForm.value.levelName = (level?.name as string)
}
//添加功能
const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            examAdd(ruleForm.value).then(res => {
                if (res.code === 1) {
                    //提示
                    ElMessage({
                        message: '保存成功',
                        type: 'success',
                        duration: 1500,
                        onClose: () => {
                            //跳转
                            router.push('/subject')
                        }
                    })
                } else {
                    ElMessage({
                        message: res.message,
                        type: 'error'
                    })
                }
            })
        }
    })
}
//重置表单功能
const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}
// 动态添加/删除选项
const addOption = () => {
    const nextChar = String.fromCharCode(65 + ruleForm.value.options.length)
    ruleForm.value.options.push({ prefix: nextChar, content: '' })
}
const removeOption = (idx: number) => {
    ruleForm.value.options.splice(idx, 1)
    // 如果删除的是当前正确答案，清空
    if (ruleForm.value.correctAnswer && !ruleForm.value.options.find((item: any) => item.prefix === ruleForm.value.correctAnswer)) {
        ruleForm.value.correctAnswer = ''
    }
}
</script>